#include "GUIMonitorSamplingPointWidget.h"
#include "ui_GUIMonitorSamplingPointWidget.h"

#include "FITK_Interface/FITKInterfaceCustomData/FITKCDMonitorSamplingPoint.h"
#include "FITK_Kernel/FITKCore/FITKOperatorRepo.h"
#include "OperatorsInterface/TreeEventOperator.h"

#include <QDoubleSpinBox>

using namespace GUI;

GUIMonitorSamplingPointWidget::GUIMonitorSamplingPointWidget(Interface::FITKCDMonitorSamplingPointManager* pManager, EventOper::ParaWidgetInterfaceOperator* oper, QWidget* parent) :
	GUIWidgetBase(parent), _oper(oper), _pManager(pManager)
{
	_ui = new Ui::GUIMonitorSamplingPointWidget();
	_ui->setupUi(this);

	init();
}

GUIMonitorSamplingPointWidget::~GUIMonitorSamplingPointWidget()
{
	if (_ui) {
		delete _ui;
		_ui = nullptr;
	}
}

void GUIMonitorSamplingPointWidget::init()
{
	setDataToWidget();
}

void GUIMonitorSamplingPointWidget::setDataToWidget()
{
	// remove old data
	while (_ui->formLayout->rowCount() > 1)
	{
		_ui->formLayout->removeRow(0);
	}

	// add data
	for (int i = 0; i < _pManager->getDataCount(); i++)
	{
		auto obj = _pManager->getDataByIndex(i);

		QString sLabel = obj->getDataObjectName();
		double* d = obj->getPosition();

		QHBoxLayout* pPositionLayout = new QHBoxLayout;
		for (int j = 0; j < 3; j++)
		{
			QDoubleSpinBox* pPosition = new QDoubleSpinBox(this);
			pPosition->setRange(-std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity());
			pPosition->setDecimals(6);
			pPosition->setValue(d[j]);
			pPosition->setProperty("row", i);
			pPosition->setProperty("col", j);
			pPositionLayout->addWidget(pPosition);
			connect(pPosition, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &GUIMonitorSamplingPointWidget::doubleSpinBoxValueChanged);
		}
		_ui->formLayout->insertRow(_ui->formLayout->rowCount() - 1, sLabel, pPositionLayout);
	}
}

void GUIMonitorSamplingPointWidget::on_pushButton_add_clicked()
{
	auto pPointItem = new Interface::FITKCDMonitorSamplingPoint();
	pPointItem->setDataObjectName("point_" + QString::number(_pManager->getDataCount()));
	_pManager->appendDataObj(pPointItem);

	setDataToWidget();
}
void GUIMonitorSamplingPointWidget::on_pushButton_remove_clicked()
{
	auto nCnt = _pManager->getDataCount();
	if (nCnt > 0)
	{
		_pManager->removeDataObj(_pManager->getDataByIndex(nCnt - 1));

		setDataToWidget();
	}
}


void GUIMonitorSamplingPointWidget::doubleSpinBoxValueChanged(double dVal)
{
	QDoubleSpinBox* pPosition = qobject_cast<QDoubleSpinBox*>(sender());
	int row = pPosition->property("row").toInt();
	int col = pPosition->property("col").toInt();

	auto d = _pManager->getDataByIndex(row)->getPosition();
	d[col] = dVal;
	_pManager->getDataByIndex(row)->setPosition(d);
}